<template>
    <div class="container py-5" style="max-width: 640px">
        <!-- 🧑 头像和用户名 -->
        <div class="mb-4" v-if="!infoLoading">
            <div class="d-flex align-items-center">
                <img :src="user.avatar || defaultAvatar" alt="Avatar" class="rounded-circle border shadow me-3"
                    style="width: 96px; height: 96px; object-fit: cover" />
                <div>
                    <h4 class="mb-3 fw-semibold">{{ user.username || '未命名用户' }}</h4>
                    <p class="text-muted mb-0">{{ user.email || '暂无邮箱绑定' }}</p>
                </div>
            </div>
        </div>

        <!-- 加载状态 -->
        <div class="text-center mb-4" v-else>
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-2">正在加载用户信息...</p>
        </div>

        <!-- 📄 用户信息展示 -->
        <div class="card p-4 mb-4" :class="theme.isDark ? 'bg-dark text-light' : ''" v-if="!infoLoading">
            <h5 class="mb-3">基础信息</h5>
            <ul class="list-unstyled">
                <li class="d-flex justify-content-between py-2 border-bottom">
                    <span class="text-muted">用户名</span>
                    <span>{{ user.username }}</span>
                </li>
                <li class="d-flex justify-content-between py-2 border-bottom">
                    <span class="text-muted">邮箱</span>
                    <span>{{ user.email }}</span>
                </li>
                <li class="d-flex justify-content-between py-2 border-bottom">
                    <span class="text-muted">手机号</span>
                    <span>{{ user.phone }}</span>
                </li>
                <li class="d-flex justify-content-between py-2 border-bottom">
                    <span class="text-muted">注册时间</span>
                    <span>{{ user.create_time }}</span>
                </li>
            </ul>
        </div>

        <!-- 加载状态 -->
        <div class="card p-4 mb-4" :class="theme.isDark ? 'bg-dark text-light' : ''" v-else>
            <div class="d-flex justify-content-center">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
            </div>
        </div>

        <!-- ✏️ 操作按钮 -->
        <div class="d-flex gap-2" v-if="!infoLoading">
            <button class="btn btn-outline-primary flex-grow-1" @click="router.push('/resetPassword')">修改密码</button>
            <button class="btn btn-outline-secondary flex-grow-1" @click="showEdit = true">编辑资料</button>
        </div>

        <!-- 加载状态 -->
        <div class="d-flex gap-2" v-else>
            <button class="btn btn-outline-primary flex-grow-1" disabled>修改密码</button>
            <button class="btn btn-outline-secondary flex-grow-1" disabled>编辑资料</button>
        </div>

        <!-- 🔧 编辑资料模态框 -->
        <Modal v-model:show="showEdit" title="编辑资料">
            <form @submit.prevent="handleSave">
                <div class="mb-3">
                    <label class="form-label">用户名</label>
                    <input v-model="editForm.username" class="form-control" />
                </div>
                <div class="mb-3">
                    <label class="form-label">邮箱</label>
                    <input v-model="editForm.email" class="form-control" />
                </div>
                <div class="mb-3">
                    <label class="form-label">手机号</label>
                    <input v-model="editForm.phone" class="form-control" />
                </div>
                <div class="d-flex justify-content-end gap-2 mt-4">
                    <button type="button" class="btn btn-secondary" @click="showEdit = false">取消</button>
                    <button type="submit" class="btn btn-primary" :disabled="loading">
                        <span v-if="loading">保存中...</span>
                        <span v-else>保存</span>
                    </button>
                </div>
            </form>
        </Modal>
    </div>
</template>

<script setup>
import { reactive, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useThemeStore } from '../store/theme';
import Modal from '../components/Modal.vue';
import { useToast } from '../composables/useToast';
import { useApi } from '../composables/useApi';

const theme = useThemeStore();
const router = useRouter();
const { success, error } = useToast();

const defaultAvatar = new URL('../assets/imgs/默认头像.png', import.meta.url).href;

const showEdit = ref(false);
const user = reactive({
    username: '',
    email: '',
    phone: '',
    avatar: '',
    create_time: ''
});

const editForm = reactive({
    username: '',
    email: '',
    phone: ''
});

// ✅ 使用 useApi 获取用户信息
const { loading: infoLoading, result, fetchData } = useApi({
    url: '/auth/info',
    method: 'get',
    manual: false
});

// ✅ 创建更新用户信息的api调用
const { loading, result: updateResult, fetchData: updateFetchData } = useApi({
    url: '/auth/update',
    method: 'put',
    manual: true
});

// ✅ 监听 result，赋值到 user / editForm
watch(result, res => {
    if (!res) return;
    const data = res.data || res;
    user.username = data.username || '';
    user.email = data.email || '';
    user.phone = data.phone || '';
    user.avatar = data.avatar || '';
    user.create_time = data.create_time || '';
    editForm.username = user.username;
    editForm.email = user.email;
    editForm.phone = user.phone || '';
});

const handleSave = async () => {
    if (!editForm.username.trim()) {
        error('用户名不能为空');
        return;
    }
    if (!editForm.email.trim()) {
        error('邮箱不能为空');
        return;
    }

    try {
        await updateFetchData({ data: editForm });
        // 通过监听updateResult获取响应数据
        const res = updateResult.value;
        console.log('更新响应:', res);
        // 根据API响应格式调整判断条件
        if (res && res.code === 0) {
            // 更新本地用户信息
            user.username = editForm.username;
            user.email = editForm.email;
            user.phone = editForm.phone;
            showEdit.value = false;
            success('资料已更新');
        } else {
            error(res?.msg || '更新失败');
        }
    } catch (err) {
        error('更新失败，请重试');
        console.error('更新用户信息失败:', err);
    }
};
</script>